import {defineConfig, loadEnv} from 'vite'
import {resolve} from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import {createHtmlPlugin} from 'vite-plugin-html'
import Components from 'unplugin-vue-components/vite'
import eslint from 'vite-plugin-eslint'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
import vue from '@vitejs/plugin-vue'
import {viteCommonjs} from '@originjs/vite-plugin-commonjs'

const getTarget = (mode: string, target: string) => {
	return loadEnv(mode, process.cwd())[target]
}

// https://vitejs.dev/config/
export default (mode: any) => defineConfig({
	server: {
		host: '0.0.0.0',
		port: 8000,
		hmr: true, // 热更新
		proxy: {
			'/api': {
				target: process.env.VITE_APP_URL,
				changeOrigin: true,
				rewrite: (path) => path.replace(/^\/api/, '')
			}
		}
	},
	plugins: [
		viteCommonjs(),
		vue(),
		createHtmlPlugin({
			entry: 'src/main.ts',
			minify: true,
			inject: {
				data: {
					title: getTarget(mode.mode, 'VITE_APP_TITLE')
				}
			}
		}),
		eslint(),
		AutoImport({
			resolvers: [ElementPlusResolver()]
		}),
		Components({
			resolvers: [ElementPlusResolver()]
		})
	],
	// target: 'esnext',
	build: {
		outDir: 'dist',
		minify: 'terser',
		// esbuild 打包更快，但是不能去除 console.log，terser打包慢，但能去除 console.log
		terserOptions: {
			compress: {
				drop_console: true,
				drop_debugger: true
			}
		},
		sourcemap: false,
		// 禁用 gzip 压缩大小报告，可略微减少打包时间
		reportCompressedSize: false,
		// 规定触发警告的 chunk 大小
		chunkSizeWarningLimit: 3000,
		rollupOptions: {
			output: {
				chunkFileNames: 'assets/js/[name]-[hash].js',
				entryFileNames: 'assets/js/[name]-[hash].js',
				assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
			}
		}
	},
	resolve: {
		alias: {
			'@': resolve(__dirname, 'src')
		}
	},
	css: {
		preprocessorOptions: {
			scss: {
				additionalData: `
          @import "@/assets/style/variables.scss";
		  		@import "@/assets/style/reset.scss";
          @import "@/assets/style/mixin.scss";
          `
			}
		}
	}
})
